import com.google.zxing.BinaryBitmap;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import com.googlecode.javacv.CanvasFrame;
import com.googlecode.javacv.FrameGrabber.Exception;
import com.googlecode.javacv.OpenCVFrameGrabber;
import com.googlecode.javacv.cpp.opencv_core.IplImage;

public class QRSensorData implements TestSensorInterface {
	
	private String qrData = null; 
	@Override
	public String getSensorData() throws Exception {
		// TODO Auto-generated method stub
		Result result = null;
		BinaryBitmap bitmap;

		
			OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);
			CanvasFrame canvasFrame = new CanvasFrame("Original stream");

			//
			grabber.start();

			IplImage frame;
			//canvasFrame.setCanvasSize(frame.width(), frame.height());
			boolean isRunning = true;
			while (isRunning) {
				if ((frame = grabber.grab()) == null)
					break;
				canvasFrame.setCanvasSize(frame.width(), frame.height());
				canvasFrame.showImage(frame);
				LuminanceSource source = new BufferedImageLuminanceSource(
						frame.getBufferedImage());
				bitmap = new BinaryBitmap(new HybridBinarizer(source));
				// binaryBitmap = new BinaryBitmap(new HybridBinarizer(
				// new BufferedImageLuminanceSource(
				// ImageIO.read(new FileInputStream(
				// )))));
				try {
					//System.out.println("trying...");
					result = new MultiFormatReader().decode(bitmap);
//					System.out.println("QR Code : " + result.getText());
					qrData = result.getText();
					isRunning = false;
					
				} catch (NotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} 


		
		// frame.getBufferedImage();
		// while (canvasFrame.isVisible() && (frame = grabber.grab()) !=
		// null) {
		// canvasFrame.showImage(frame);
		// LuminanceSource source = new
		// BufferedImageLuminanceSource(frame.getBufferedImage());
		// bitmap = new BinaryBitmap(new HybridBinarizer(source));
		// // binaryBitmap = new BinaryBitmap(new HybridBinarizer(
		// // new BufferedImageLuminanceSource(
		// // ImageIO.read(new FileInputStream(
		// // )))));
		// result = new MultiFormatReader().decode(bitmap);
		// System.out.println("QR Code : " + result.getText());
		// }

		
		grabber.stop();
		
		canvasFrame.dispose();
		
		if(qrData!= null){
			return qrData;
		}else{
			return null;
		}
		
	}
}
